package com.course.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.course.entity.Admin;
import com.course.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdminHandler {
    @Autowired
    private AdminRepository adminRepository;

    @GetMapping("/findAll")
    public List<Admin> findAll() {
        return adminRepository.findAll();
    }

    @GetMapping("/findById/{id}")
    public Admin findById(@PathVariable("id") Integer id) {
        return adminRepository.findById(id).get();
    }

    @PutMapping("/edit")
    public String update(@RequestBody Admin admin) {
        Admin result = adminRepository.save(admin);
        if (result != null) {
            return "success";
        } else {
            return "error";
        }
    }

    @PostMapping("/checkPass")
    public String checkPass(@RequestBody String resq) {
        Admin admin = adminRepository.findAdminByAccount("admin");
        String adminPass = admin.getPassword();

        JSONObject jsonObject = JSON.parseObject(resq);
        String oldPass = jsonObject.getString("oldPass");

        String pass = jsonObject.getString("pass");

        if (adminPass.equals(oldPass)) {
            admin.setPassword(pass);
            adminRepository.save(admin);
            return "success";
        }

        return "error";
    }
}
